package db

import (
	"fmt"
	"time"

	"gitee.com/diandisoft/ant_forest_energy_web_server/models"
	"gopkg.in/mgo.v2/bson"
)

type Dao struct{}

// 插入采集记录
// 要检查是否有重复的记录，因为手机端有可能发送重复记录
func (u Dao) InsertCollentRecords(records models.CollentRecords, targetUserID string) error {
	s := Session.Clone()
	defer s.Close()
	col := s.DB(Mongo.Database).C(models.MG_CollectionCollentRecords)
	// 遍历每条能量采集记录，进行查重以及插入
	for _, v := range records.Energys {
		CollentTime := time.Unix(v.CollentTime, 0)
		collentDay, _ := time.Parse("2006-01-02", CollentTime.Format("2006-01-02"))
		selector := bson.M{"ant_id": targetUserID, "collent_day": collentDay}
		if count, err := col.Find(selector).Count(); err == nil {
			if count == 0 {
				var d = models.MG_CollentRecords{}
				d.AntId = targetUserID
				d.CollentDay = collentDay
				d.Energys = []models.MG_Energy{models.MG_Energy{v.TargetAntId, v.EnergyNumber, CollentTime}}
				if err := col.Insert(d); err != nil {
					return err
				}
				fmt.Println("新增能量采集记录:------")
				fmt.Println(d)
			} else {
				subSelector := bson.M{"ant_id": targetUserID,
					"collent_day": collentDay,
					"energys": bson.M{"$elemMatch": bson.M{
						"target_ant_id": v.TargetAntId,
						"energy_number": v.EnergyNumber,
						"collent_time":  CollentTime}}}
				if count, err = col.Find(subSelector).Count(); err == nil {
					if count == 0 {
						fmt.Printf("新增能量采集的记录：ant_id:%s  num:%d   time:%v\n", v.TargetAntId, v.EnergyNumber, CollentTime)
						data := bson.M{"target_ant_id": v.TargetAntId,
							"energy_number": v.EnergyNumber,
							"collent_time":  CollentTime}
						col.Update(selector, bson.M{"$push": bson.M{"energys": data}})
					}
				} else {
					return err
				}
			}
		} else {
			return err
		}
	}
	return nil
}

func (u Dao) GetLastCollentTime(targetUserID string, result *time.Time) error {
	s := Session.Clone()
	defer s.Close()
	col := s.DB(Mongo.Database).C(models.MG_CollectionCollentRecords)
	// 查询的文档条件
	selector := bson.M{"ant_id": targetUserID}
	// 查询的单个字段(collent_day)
	filedor := bson.M{"collent_day": 1}
	// 进行查询
	var d = models.MG_CollentRecords{}
	if err := col.Find(selector).Sort("-collent_day").Select(filedor).One(&d); err == nil {
		*result = d.CollentDay
		fmt.Println(result)
	} else {
		return err
	}
	return nil
}
